package com.jxau.mall.common.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jxau.mall.common.enums.ResponseEnum;
import com.jxau.mall.common.util.JwtUtils;
import com.jxau.mall.common.util.ResponseVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @program: shop
 * @description: 登录拦截器的工具类
 * @author: guojiani
 * @create: 2025-04-24 21:32
 **/
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("Authorization");
        //如果token为空，用户未登录。否则，如果token过期，登录过期，否则通过拦截并存储用户信息
        if(token == null){
            // 将response输出转换成json格式
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json;charset=UTF-8");
            objectMapper.writeValue(response.getWriter(), ResponseVO.fail(ResponseEnum.USER_NOT_LOGGED_IN));
            return false;
        }else if(JwtUtils.isExpired(token)){
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json;charset=UTF-8");
            objectMapper.writeValue(response.getWriter(), ResponseVO.fail(ResponseEnum.PERMISSION_TOKEN_EXPIRED));
            return false;
        }else {
            // 获取令牌中的用户信息，在登录时存储了用户的userId
            Long id = JwtUtils.parseToken(token).get("userId", Long.class);
        }
        return true;
    }
}
